package org.marsdonne.commons;

import graphql.relay.*;

import java.util.List;
import java.util.stream.Collectors;

public interface GraphQLPageable<T extends Identifiable> {
    default List<Edge<T>> getEdges(List<T> records, int first) {
        return records.stream().limit(first)
                .map(node -> new DefaultEdge<>(node, new DefaultConnectionCursor(String.valueOf(node.getId()))))
                .collect(Collectors.toList());
    }

    default PageInfo getPageInfo(int first, Long after, Long minId, Long maxId, long size) {
        return new DefaultPageInfo(
                new DefaultConnectionCursor((minId == null) ? "0" : minId.toString()),
                new DefaultConnectionCursor((maxId == null) ? "0" : maxId.toString()),
                (minId == null || after == null) ? false : after > minId,
                size > first);
    }

    default Connection<T> getConnection(List<Edge<T>> edges, PageInfo pageInfo) {
        return new DefaultConnection<>(edges, pageInfo);
    }

    default Connection<T> getConnection(List<T> list, int first, Long after, Long minId, Long maxId) {
        return getConnection(getEdges(list, first), getPageInfo(first, after, minId, maxId, list.size()));
    }
}
